package com.ynet.middleground.oss.common;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ynet.core.common.ServiceResult;

/**
 * @author liulx
 * @description token 失效异常处理
 * @date 2020-10-19 10:52
 */
@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setStatus(HttpStatus.OK.value());
        httpServletResponse.setHeader("Content-Type", "application/json;charset=UTF-8");

        ServiceResult<Object> serviceResult = new ServiceResult<>();
        if (e.getCause() instanceof InvalidTokenException) {
            serviceResult.setError("ECOS1000", "无效 token");
        } else {
            serviceResult.setError("ECOS1001", "无权限");
        }

        httpServletResponse.getWriter().write(JSON.toJSONString(serviceResult));
    }

}
